<template>
  <div class="product-manage">
    <!-- 搜索和操作栏 -->
    <div class="operation-bar">
      <div class="search-area">
        <el-input
          v-model="searchQuery"
          placeholder="搜索商品"
          prefix-icon="el-icon-search"
          clearable
          @clear="handleSearch"
          @keyup.enter.native="handleSearch"
          class="search-input"
        ></el-input>
        <el-select v-model="selectedCategory" placeholder="商品分类" clearable @change="handleSearch">
          <el-option
            v-for="item in categories"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加商品</el-button>
    </div>

    <!-- 商品列表 -->
    <el-table
      v-loading="loading"
      :data="products"
      border
      style="width: 100%">
      <el-table-column
        prop="id"
        label="ID"
        width="80">
      </el-table-column>
      <el-table-column
        label="商品图片"
        width="100">
        <template slot-scope="scope">
          <el-image
            style="width: 60px; height: 60px"
            :src="scope.row.imageUrl || '/uploads/products/default.jpg'"
            :preview-src-list="[scope.row.imageUrl || '/uploads/products/default.jpg']">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="商品名称"
        min-width="200">
      </el-table-column>
      <el-table-column
        prop="category"
        label="分类"
        width="120">
        <template slot-scope="scope">
          {{ getCategoryLabel(scope.row.category) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="price"
        label="价格"
        width="120">
        <template slot-scope="scope">
          ¥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column
        prop="stock"
        label="库存"
        width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.stock < 10 ? 'danger' : 'success'">
            {{ scope.row.stock }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="sales"
        label="销量"
        width="100">
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="200"
        fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加商品' : '编辑商品'"
      :visible.sync="dialogVisible"
      width="50%"
      @close="resetForm">
      <el-form ref="productForm" :model="productForm" :rules="rules" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="category">
          <el-select v-model="productForm.category" placeholder="请选择商品分类">
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number
            v-model="productForm.price"
            :precision="2"
            :step="0.1"
            :min="0"
            controls-position="right">
          </el-input-number>
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input-number
            v-model="productForm.stock"
            :min="0"
            controls-position="right">
          </el-input-number>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            class="product-image-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload">
            <img v-if="productForm.imageUrl" :src="productForm.imageUrl" class="product-image">
            <i v-else class="el-icon-plus product-image-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            type="textarea"
            v-model="productForm.description"
            :rows="4"
            placeholder="请输入商品描述">
          </el-input>
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-switch
            v-model="productForm.status"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getProductList, createProduct, updateProduct, deleteProduct, uploadProductImage } from '@/api/product'

export default {
  name: 'ProductManage',
  data() {
    return {
      loading: false,
      searchQuery: '',
      selectedCategory: '',
      products: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      categories: [
        { value: 'food', label: '宠物食品' },
        { value: 'toys', label: '玩具用品' },
        { value: 'health', label: '保健品' },
        { value: 'daily', label: '日用品' }
      ],
      dialogVisible: false,
      dialogType: 'add', // 'add' or 'edit'
      productForm: {
        name: '',
        category: '',
        price: 0,
        stock: 0,
        imageUrl: '',
        description: '',
        status: 1
      },
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '请输入商品库存', trigger: 'blur' }
        ]
      },
      uploadUrl: process.env.VUE_APP_BASE_API + '/api/files/upload'
    }
  },
  created() {
    this.fetchProducts()
  },
  methods: {
    async fetchProducts() {
      try {
        this.loading = true
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchQuery,
          category: this.selectedCategory
        }
        const response = await getProductList(params)
        this.products = response.list
        this.total = response.total
      } catch (error) {
        this.$message.error('获取商品列表失败')
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      this.currentPage = 1
      this.fetchProducts()
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.fetchProducts()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchProducts()
    },

    getCategoryLabel(value) {
      const category = this.categories.find(item => item.value === value)
      return category ? category.label : '未分类'
    },

    handleAdd() {
      this.dialogType = 'add'
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.dialogType = 'edit'
      this.productForm = { ...row }
      this.dialogVisible = true
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该商品吗？', '提示', {
          type: 'warning'
        })
        await deleteProduct(row.id)
        this.$message.success('删除成功')
        this.fetchProducts()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },

    async handleStatusChange(row) {
      try {
        await updateProduct(row.id, { status: row.status })
        this.$message.success('状态更新成功')
      } catch (error) {
        this.$message.error('状态更新失败')
        row.status = row.status === 1 ? 0 : 1 // 恢复状态
      }
    },

    resetForm() {
      this.$refs.productForm?.resetFields()
      this.productForm = {
        name: '',
        category: '',
        price: 0,
        stock: 0,
        imageUrl: '',
        description: '',
        status: 1
      }
    },

    async submitForm() {
      try {
        await this.$refs.productForm.validate()
        if (this.dialogType === 'add') {
          await createProduct(this.productForm)
          this.$message.success('添加成功')
        } else {
          await updateProduct(this.productForm.id, this.productForm)
          this.$message.success('更新成功')
        }
        this.dialogVisible = false
        this.fetchProducts()
      } catch (error) {
        if (error !== false) {
          this.$message.error(this.dialogType === 'add' ? '添加失败' : '更新失败')
        }
      }
    },

    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
        return false
      }
      return true
    },

    handleUploadSuccess(response) {
      this.productForm.imageUrl = response.data
      this.$message.success('图片上传成功')
    }
  }
}
</script>

<style lang="scss" scoped>
.product-manage {
  padding: 20px;

  .operation-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .search-area {
      display: flex;
      gap: 20px;

      .search-input {
        width: 300px;
      }
    }
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }
}

.product-image-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;

    &:hover {
      border-color: #409EFF;
    }
  }
}

.product-image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.product-image {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}
</style> 